package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"

	"leeframe/configs"
	"leeframe/initialize"
	"leeframe/internal/pkg/env"
	"leeframe/internal/pkg/logger"
	routers "leeframe/internal/router"
)

func init() {
	// 初始化
	initialize.Setup()
}

// @title leeframe
// @version 1.0
// @description An example of leeframe
// @termsOfService https://xxx
// @license.name MIT
// @license.url https://xxx
func main() {
	// gin模式设置
	gin.SetMode(env.Mode())

	routersInit := routers.InitRouter()
	readTimeout := configs.Get().Server.ReadTimeout * time.Second
	writeTimeout := configs.Get().Server.WriteTimeout * time.Second
	endPoint := fmt.Sprintf(":%d", configs.Get().Server.HttpPort)
	maxHeaderBytes := 1 << 20

	server := &http.Server{
		Addr:           endPoint,
		Handler:        routersInit,
		ReadTimeout:    readTimeout,
		WriteTimeout:   writeTimeout,
		MaxHeaderBytes: maxHeaderBytes,
	}

	go func() {
		if err := server.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
			logger.Error("listen and serve error: ", err)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	logger.Info("Shutdown server...")
	if err := server.Shutdown(ctx); err != nil {
		logger.Error("Server shutdown error: ", err)
	}
	logger.Info("Server exits.")
}
